package rexsee.barcode;

import rexsee.barcode.BarcodeCaptureDialog.OnScanSuccessed;
import rexsee.core.browser.Browser;
import rexsee.core.browser.clazz.JavascriptInterface;
import rexsee.core.utilities.Escape;
import android.content.Context;
import android.graphics.Bitmap;

public class RexseeBarcode implements JavascriptInterface {

	public static final String INTERFACE_NAME = "Barcode";
	@Override
	public String getInterfaceName() {
		return mBrowser.application.resources.prefix + INTERFACE_NAME;
	}
	@Override
	public JavascriptInterface getInheritInterface(Browser childBrowser) {
		return this;
	}
	@Override
	public JavascriptInterface getNewInterface(Browser childBrowser) {
		return new RexseeBarcode(childBrowser);
	}

	public static final String EVENT_ONBARCODESCANSUCCESSED = "onBarcodeScanSuccessed";
	public static final String EVENT_ONBARCODESCANFAILED = "onBarcodeScanFailed";

	private final Browser mBrowser;

	public RexseeBarcode(Browser browser) {
		mBrowser = browser;
		browser.eventList.add(EVENT_ONBARCODESCANSUCCESSED);
		browser.eventList.add(EVENT_ONBARCODESCANFAILED);
	}

	public void start(boolean beep, boolean vibrate, boolean flash) {
		try {
			final OnScanSuccessed onScanSuccessed = new OnScanSuccessed() {
				@Override
				public void run(Context context, Bitmap bitmap, String format, String text, String type, String metaData, String content) {
					if (text == null && type == null && content == null) {
						mBrowser.eventList.run(EVENT_ONBARCODESCANFAILED, new String[]{"User canceled."});
					} else {
						mBrowser.eventList.run(EVENT_ONBARCODESCANSUCCESSED, new String[]{Escape.escape(text), Escape.escape(format), Escape.escape(type), Escape.escape(metaData), Escape.escape(content)});
					}
				}
			};
			BarcodeCaptureDialog dialog = new BarcodeCaptureDialog(mBrowser.getContext(), onScanSuccessed, beep, vibrate, flash);
			dialog.startDialog();
		} catch (Exception e) {
			mBrowser.eventList.run(EVENT_ONBARCODESCANFAILED, new String[]{"Exception:" + e.getLocalizedMessage()});
		}
	}

}
